Module# 12: Java IO Streams and
File Lecture#44: IO with Character Streams
// Example 44.1: Reading String, Integer
and Double from Keyboard
import java.io.*;
public class KeyboardReading{
public static void main(String args[]) throws IOException
{
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a String:
");
String str1 = b.readLine();
System.out.println("Entered String
value is: " + str1);
System.out.println("Enter a whole
number: ");
String str2 = b.readLine();
int x = Integer.parseInt(str2);
System.out.println("Enter a double
value: ");
String str3 = b.readLine();
double y = Double.parseDouble(str3);
if(x > y)
System.out.println("First number
" +x + " is greater than second number " + y);
else
System.out.println("First number
" +x + " is less than second number " + y);
b.close();
}
}
// Example 44.2: Calculator using BufferedReader
import java.io.*;
class InterestCalculator {
public static void main(String args[ ] ) {
Float principalAmount
= new Float(0);
Float rateOfInterest
= new Float(0);
int numberOfYears = 0;
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
String tempString;
System.out.print("Enter Principal
Amount: ");
System.out.flush();
tempString = b.readLine();
principalAmount = Float.valueOf(tempString);
System.out.print("Enter Rate of
Interest: ");
System.out.flush();
tempString = b.readLine();
rateOfInterest = Float.valueOf(tempString);
System.out.print("Enter Number of
Years:");
System.out.flush();
tempString = b.readLine();
numberOfYears = Integer.parseInt(tempString);
// Input is over: calculate the interest
int interestTotal = principalAmount*rateOfInterest*numberOfYears;
System.out.println("Total Interest
= " + interestTotal);
}
}
// Example 44.3:
Copying files using FileReader and FileWriter
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyChars
{
public static void main(String[] args) throws IOException
{
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new FileReader("nptel.txt");
outputStream = new FileWriter("characteroutput.txt");
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}